package main

import (
	"fmt"
	"slices"
)

func trap(height []int) int {
	res, sum := 0, 0
	i := 0
	iHeight := height[i]
	for j, jHeight := range height {
		if jHeight >= iHeight {
			res += sum
			sum = 0
			i, iHeight = j, jHeight
		} else {
			sum += iHeight - jHeight
		}
	}
	sum = 0
	if i != len(height)-1 {
		revHeight := height[i:]
		slices.Reverse(revHeight)
		i, iHeight = 0, revHeight[0]
		for k, kHeight := range revHeight {
			if kHeight >= iHeight {
				res += sum
				sum = 0
				i, iHeight = k, kHeight
			} else {
				sum += iHeight - kHeight
			}
		}
	}
	return res
}

func main() {
	height := []int{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}
	res := trap(height)
	fmt.Println(res)
}
